<template>
  <div class="category-page">
    <article-list
      :articles="article.data.data"
      :fetching="article.fetching"
      :pagination="article.data.pagination"
      @loadmore="loadmoreArticles"
    />
  </div>
</template>

<script>
import ArticleList from "@/components/archive/list.vue";
import { useEnhandle } from "../enhandle";
import { computed, defineComponent, onBeforeMount, watch } from "vue";
import { nextScreen, scrollToTop } from "../utils/effects";
import { onClient } from "@/universal";

export default defineComponent({
  name: "Category",
  components: {
    ArticleList,
  },
  props: {
    categorySlug: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    const { store } = useEnhandle();
    const article = computed(() => store.state.article.list);

    const fetchArticles = (params) => {
      return store.dispatch("article/fetchList", params);
    };

    const loadmoreArticles = async () => {
      await fetchArticles({
        categorySlug: props.categorySlug,
        page: article.value.data.pagination.page + 1
      });
      onClient(nextScreen)
    };

    const fetchAllData = (category_slug) => {
      onClient(scrollToTop)
      return Promise.all([
        fetchArticles({ category_slug })
      ])
    }

    onBeforeMount(() => {
      watch(
        () => props.categorySlug,
        (categorySlug) => fetchAllData(categorySlug)
      );
    });

    fetchAllData(props.categorySlug)

    return {
      article,
      loadmoreArticles,
    };
  },
});
</script>
